//
//  SEGIBluetooth.m
//  ExcellentHome
//
//  Created by Chiang on 16/8/3.
//  Copyright © 2016年 陈区. All rights reserved.
//

#import "SEGIBluetooth.h"

static NSString *const kServiceUUID = @"FFF1";
static NSString *const kDeviceName  = @"201601012123";
static NSString *const kCommand     = @"30100203000001010F020A100E32FA34DD000118";

@interface SEGIBluetooth()<CBCentralManagerDelegate,CBPeripheralDelegate>
{
    CBCentralManager *manager;
    NSTimer *connectTimer;
    NSMutableArray *muArray;
}
@property (nonatomic, strong) NSMutableArray *dicoveredPeripherals;
@property (nonatomic, strong) CBPeripheral *peripheral ;
@end

@implementation SEGIBluetooth

+ (SEGIBluetooth *)sharedManager
{
    static SEGIBluetooth *sharedManager = nil;
    if(sharedManager){return sharedManager;}
    sharedManager = [[SEGIBluetooth alloc] init];
    return sharedManager;
}

-(void)setUp{
    manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],CBCentralManagerScanOptionAllowDuplicatesKey, nil];
    [manager scanForPeripheralsWithServices:nil options:options];
}

-(void)centralManagerDidUpdateState:(CBCentralManager *)central{
    switch (central.state) {
            //判断状态开始扫瞄周围设备 第一个参数为空则会扫瞄所有的可连接设备  你可以
            //指定一个CBUUID对象 从而只扫瞄注册用指定服务的设备
            //scanForPeripheralsWithServices方法调用完后会调用代理CBCentralManagerDelegate的
            //- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI方法
        case CBCentralManagerStatePoweredOn:
            [manager scanForPeripheralsWithServices:nil options:Nil];
            break;
            
        default:
            break;
    }
}
-   (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
    
    if ([peripheral.name isEqualToString:self.deviceName]) {
        [manager stopScan];
        self.peripheral = peripheral;
        [manager connectPeripheral:self.peripheral options:Nil];
    }
    
}
-   (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
    
    self.peripheral.delegate =self;
    [self.peripheral discoverServices:nil];
    
}

//失去链接
-(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
}
//链接失败
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error
{
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    
    for(CBService *service in peripheral.services){
        if([service.UUID.UUIDString isEqualToString:@"FFF0"]){
            CBUUID *FFF1 = [CBUUID UUIDWithString:kServiceUUID];
            [peripheral discoverCharacteristics:@[FFF1] forService:service];
        }
    }
}

-   (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    
    for(CBCharacteristic  *character in service.characteristics){
        NSString *characteristc = character.UUID.UUIDString;
        if([characteristc  isEqualToString:@"FFF1"]){
            //加密转换
            NSData *data = [self stringToByte:kCommand];
            //写入命令
            [peripheral writeValue:data forCharacteristic:character type:CBCharacteristicWriteWithResponse];
        }
    }
}
-(NSData*)stringToByte:(NSString*)string
{
    NSString *hexString=[[string uppercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ([hexString length]%2!=0) {
        return nil;
    }
    Byte tempbyt[1]={0};
    NSMutableData* bytes=[NSMutableData data];
    for(int i=0;i<[hexString length];i++)
    {
        unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
        int int_ch1;
        if(hex_char1 >= '0' && hex_char1 <='9')
            int_ch1 = (hex_char1-48)*16;   //// 0 的Ascll - 48
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65
        else
            return nil;
        i++;
        
        unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)
        int int_ch2;
        if(hex_char2 >= '0' && hex_char2 <='9')
            int_ch2 = (hex_char2-48); //// 0 的Ascll - 48
        else if(hex_char2 >= 'A' && hex_char2 <='F')
            int_ch2 = hex_char2-55; //// A 的Ascll - 65
        else
            return nil;
        
        tempbyt[0] = int_ch1+int_ch2;  ///将转化后的数放入Byte数组里
        [bytes appendBytes:tempbyt length:1];
    }
    return bytes;
}
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error
{
    if(!error){
        [self.delegate didWriteData];
    }else
    {
        [manager connectPeripheral:self.peripheral options:nil];
    }
}

@end
